package io.sdl.service.impl;

import io.sdl.common.service.impl.BaseServiceImpl;
import io.sdl.common.utils.ConvertUtils;
import io.sdl.dao.SdlDiariesDao;
import io.sdl.dto.SdlDiariesDTO;
import io.sdl.entity.SdlDiariesEntity;
import io.sdl.service.SdlDiariesService;
import io.sdl.utils.StringHandlsUtils;
import io.sdl.common.utils.UploadFileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


@Service("sdlDiariesService")
public class SdlDiariesServiceImpl extends BaseServiceImpl<SdlDiariesDao, SdlDiariesEntity> implements SdlDiariesService {

    // 文件存储根路径
    @Value("${file.upload-dir}")
    private String uploadDirResource;


    @Override
    public List<SdlDiariesDTO> selectByUserId(Long userId,Long roleId, Integer page, Integer limit) {

        List<SdlDiariesEntity> sdlDiariesEntities = baseDao.selectByUserId(userId,roleId, page - 1, limit);
        sdlDiariesEntities.forEach(diariesEntity -> {
            diariesEntity.setImagesList(StringHandlsUtils.splitImageUrlsToList(diariesEntity.getImages()));
        });
        return ConvertUtils.sourceToTarget(sdlDiariesEntities, SdlDiariesDTO.class);
    }


    @Override
    public int getNum(Long userId) {
        return baseDao.getNum(userId);
    }

    @Override
    @Transactional
    public Integer saveUploadedFile(MultipartFile file, Long id) {

        try {

            String accessUrl = "/uploads/" + UploadFileUtils.uploadFile(file);
            // 使用selectForUpdate加锁
            SdlDiariesEntity diariesEntity = baseDao.selectByIdForUpdate(id);

            diariesEntity.setImages(diariesEntity.getImages() != null ?
                    (diariesEntity.getImages() + "," + accessUrl) : accessUrl);

            return baseDao.updateById(diariesEntity);
        } catch (IOException e) {
            throw new RuntimeException("文件存储失败", e);
        }
    }

    @Override
    public SdlDiariesEntity getDiariesDetail(Long id) {
        SdlDiariesEntity diariesEntity = baseDao.selectById(id);

        diariesEntity.setImagesList(StringHandlsUtils.splitImageUrlsToList(diariesEntity.getImages()));

        return diariesEntity;
    }


}